package com.internship.javawebinternship.controller;

import com.alibaba.fastjson.JSONObject;
import com.internship.javawebinternship.repository.AccountRepository;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UploadExcelController {

    @Autowired
    private AccountRepository accountRepository;
    private static final Logger LOGGER = LoggerFactory.getLogger(UploadExcelController.class);
    AccountController accountController = new AccountController();

    @PostMapping("/uploadExcel")
//    @ResponseBody
    public Object uploadExcel(@RequestParam("file") MultipartFile file,
                              HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Map<String, Object> result = new HashMap<>();

        if (forceLogOut(request)) {
            result.put("result", "-1");
            result.put("msg", "您的账号已在其他地方登录，您已被强制下线。若需要继续操作，请重新登录并注意账号安全");
            JSONObject object = new JSONObject(result);
            return object;
        }

        try {
            if (!session.getAttribute("authority").equals("0")) {
                result.put("result", "0");
                result.put("msg", "很抱歉，您无权限进行本操作，请联系管理员以获得帮助");
                JSONObject object = new JSONObject(result);
                return object;
            }
        } catch (NullPointerException e) {
            result.put("result", "0");
            result.put("msg", "您似乎尚未登录，请登录后重试");
            JSONObject object = new JSONObject(result);
            return object;
        }

        if (file.isEmpty()) {
            result.put("result", "0");
            result.put("msg", "请选择文件");

            JSONObject object = new JSONObject(result);//使用JSONObject，将map转化为json数据
            return object;//返回json数据给前端
        }

        String fileName = file.getOriginalFilename();

        if (!fileName.split("\\.")[1].equals("xls") && !fileName.split("\\.")[1].equals("xlsx")) {
            result.put("result", "0");
            result.put("msg", "文件类型不正确，请上传xls或者xlsx格式的文件");

            JSONObject object = new JSONObject(result);//使用JSONObject，将map转化为json数据
            return object;//返回json数据给前端
        }

        String filePath = "excelUploaded/";
        File dest = new File(filePath);
        if (!dest.exists())
            dest.mkdir();

        String[] Name = dest.list();
        Date DATE = new Date();

        //自动删除7天前上传的文件
        for (String i : Name) {
            File temp = new File("excelUploaded/" + i);
            if (!temp.getName().equals("example.xlsx") && DATE.getTime() - temp.lastModified() > 604800000) {
                try {
                    File del = new File(temp.getAbsolutePath());
                    if (del.delete()) {
                        LOGGER.info("旧文件删除成功");
                    }
                } catch (Exception e) {
                    LOGGER.info("旧文件删除失败");
                }
            }
        }

        try {
            File newFile = new File(dest.getAbsolutePath() + File.separator + fileName);
            file.transferTo(newFile);
            LOGGER.info("上传成功");
            result.put("result", "1");
            session.setAttribute("fileName", fileName);
            JSONObject object = new JSONObject(result);//使用JSONObject，将map转化为json数据
            return object;//返回json数据给前端
        } catch (IOException e) {
            LOGGER.error(e.toString(), e);
        }
        result.put("result", "0");
        JSONObject object = new JSONObject(result);//使用JSONObject，将map转化为json数据
        return object;//返回json数据给前端

    }

    public boolean forceLogOut(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        boolean status;
        try {
            if (session == null) {
                status = false;
                return status;
            }
            if (!session.getId().equals(accountRepository.findByStuempno((String) session.getAttribute("no")).get(0).getSessionid())) {
                status = true;
                session.invalidate();
            } else {
                status = false;
            }
        } catch (Exception e) {
//        } catch (NullPointerException e) {
            status = true;
            session.invalidate();
            return status;
        }
        return status;
    }
}
